package com.woniuxy.ams.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis配置类
 * @author fyx
 */
@Configuration
@EnableCaching
public class RedisConfig {
    /**
     * 基本配置
     *
     * @param connectionFactory 注入redis连接工厂
     * @return 生成bean redisTemplate
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // 设置连接工厂
        redisTemplate.setConnectionFactory(connectionFactory);
        //redis将传入的对象进行序列化和序列化
        redisTemplate.setKeySerializer(RedisSerializer.string());
        //设置value的String类型
        redisTemplate.setValueSerializer(RedisSerializer.json());
        //hash类型
        redisTemplate.setHashKeySerializer(RedisSerializer.string());
        redisTemplate.setHashValueSerializer(RedisSerializer.json());
        return redisTemplate;
    }

    /**
     * 配置 springCache整合redis的配置
     * @return 生成RedisCacheConfiguration bean
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration() {
        //默认缓存配置, 通过jackson进行序列化配置 给SpringCache使用
        return RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
    }
}
